extends Node
class_name HealthComponent

# 信号，用于通知生命值变化和死亡
signal health_changed(old_value: float, new_value: float)
signal died

# 导出属性，允许在编辑器中配置
@export var max_health: float = 100.0
@export var is_invincible: bool = false

# 当前生命值
var current_health: float = max_health

func _ready() -> void:
	# 初始化当前生命值为最大生命值
	current_health = max_health

# 受到伤害
func take_damage(amount: float) -> void:
	if is_invincible or amount <= 0 or current_health <= 0:
		return
	
	var old_health = current_health
	current_health = max(0, current_health - amount)
	
	# 发出生命值变化信号
	health_changed.emit(old_health, current_health)
	
	# 如果生命值为0，发出死亡信号
	if current_health <= 0:
		died.emit()

# 恢复生命
func heal(amount: float) -> void:
	if amount <= 0:
		return
	
	var old_health = current_health
	current_health = min(max_health, current_health + amount)
	
	# 发出生命值变化信号
	health_changed.emit(old_health, current_health)

# 设置生命值（直接设置）
func set_health(value: float) -> void:
	var old_health = current_health
	current_health = clamp(value, 0, max_health)
	
	# 发出生命值变化信号
	health_changed.emit(old_health, current_health)
	
	# 如果生命值为0，发出死亡信号
	if current_health <= 0:
		died.emit()

# 获取当前生命值
func get_health() -> float:
	return current_health

# 获取最大生命值
func get_max_health() -> float:
	return max_health

# 设置无敌状态
func set_invincible(value: bool) -> void:
	is_invincible = value
